package com.honeywen.mymvc.leetcode;

/**
 * @author weiw@opera.com
 * @date 2018/7/16 下午8:09
 */
public class ReverseInteger {

    public static void main(String[] args) {
        System.out.println(reverse2(-123));


    }

    public static int reverse(int x) {

        int y = 0;

        while (x != 0) {

            if (y > Integer.MAX_VALUE / 10 || y < Integer.MIN_VALUE / 10) {
                return 0;
            }

            y = y * 10 + x % 10;

            x = x / 10;
        }


        return y;

    }

    public static int reverse2(int x) {

        if (x == Integer.MIN_VALUE) {
            return 0;
        }

        boolean positive = x < 0;

        if (positive) {
            x = -x;
        }
        String n = String.valueOf(x);

        char[] chars = n.toCharArray();

        StringBuilder sb = new StringBuilder();
        for (int len = chars.length, i = len - 1; i >= 0; i--) {
            sb.append(chars[i]);
        }
        String result = sb.toString();

        try {
            if (positive) {

                return -Integer.parseInt(result);
            } else {
                return Integer.parseInt(result);
            }

        } catch (NumberFormatException e) {
            return 0;
        }

    }
}
